import PageWrapper from "@/components/PageWrapper";
import { getComponent } from "@/components/QuestionComponents";
import getQuestionById from "@/services/question";
import { Button, Form, Input, message } from "antd";
import styles from "../question.module.scss";
import { useRouter } from "next/router";

type PropsType = {
  questionId: string;
  code: number;
  message?: string;
  result?: {
    id: string;
    title: string;
    desc?: string;
    isDeleted?: boolean;
    isPublished?: boolean;
    componentList?: Array<any>;
  };
};

export default function Question(props: PropsType) {
  const { questionId, code, message: msg, result } = props;
  const { title = "", desc = "", componentList = [] } = result || {};
  const router = useRouter();

  if (code > 0) {
    return (
      <PageWrapper title="错误">
        <div style={{ marginTop: "6rem", textAlign: "center" }}>
          <h2>错误</h2>
          <p>{msg}</p>
        </div>
      </PageWrapper>
    );
  }

  const ComponentListElem = componentList.map((c) => {
    const ComponentElem = getComponent(c);
    return <div key={c.id}>{ComponentElem}</div>;
  });

  const onFinish = async (values: any) => {
    try {
      const res = await fetch("/api/answer", {
        method: "POST",
        body: JSON.stringify(values),
        headers: {
          "Content-Type": "application/json",
        },
      });
      router.push(res.url);
    } catch (err) {
      console.log(err);
    }
  };

  const onFinishFailed = () => {
    message.error("请填写完整");
  };

  return (
    <PageWrapper title={title} desc={desc}>
      <Form
        layout="vertical"
        initialValues={{ questionId }}
        onFinish={onFinish}
        className={styles.from}
        onFinishFailed={onFinishFailed}
      >
        {ComponentListElem}
        <Form.Item name="questionId" hidden>
          <Input value={questionId} />
        </Form.Item>
        <Form.Item className="submit-button">
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </PageWrapper>
  );
}

export async function getServerSideProps(context: any) {
  const { questionId } = context.params;
  const data = await getQuestionById(questionId);

  return {
    props: {
      ...data,
      questionId,
    },
  };
}
